package com.mz.ozy.activity.me;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SlidingTabLayout;
import com.mz.ozy.R;
import com.mz.ozy.activity.shop.CarActivity;
import com.mz.ozy.activity.shop.SearchActivity;
import com.mz.ozy.activity.shop.ShopDetailActivity;
import com.mz.ozy.activity.shop.SortSearchActivity;
import com.mz.ozy.adapter.ObShopAdapter;
import com.mz.ozy.adapter.ObShopFragmentApader;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.ObShopBean;
import com.mz.ozy.bean.ObShopTitleBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.fragment.ObShopFragment;
import com.mz.ozy.mvp.presenter.ObShopPersenter;
import com.mz.ozy.mvp.view.ObShopContract;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.ob.BaseDetailFrag;
import com.mz.ozy.widget.ob.DetailScrollStateListener;
import com.mz.ozy.widget.ob.DetailScrollView;
import com.mz.ozy.widget.ob.MatchViewPager;
import com.mz.ozy.widget.ob.ObservableScrollView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.sobot.chat.ZCSobotApi;
import com.sobot.chat.api.model.Information;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author wansong
 * @description:欧花商城
 * @date :2020/9/24 15:01
 */
public class ObShopActivity extends BaseActivity<ObShopContract.View, ObShopPersenter> implements ObShopContract.View {

    @BindView(R.id.ob_shop_tab)
    SlidingTabLayout ob_shop_tab;
    @BindView(R.id.tv_search)
    TextView tv_search;
    @BindView(R.id.iv_shop_back)
    ImageView iv_shop_back;
    @BindView(R.id.vp_ob_shop_banner)
    ViewPager vp_ob_shop_banner;
    @BindView(R.id.iv_ob_shop_vip)
    ImageView iv_ob_shop_vip;
    @BindView(R.id.vp_ob_shop)
    ViewPager vp_ob_shop;
    @BindView(R.id.rv_ob_shop)
    RecyclerView rv_ob_shop;
    @BindView(R.id.rg_ob_shop)
    RadioGroup rg_ob_shop;
    @BindView(R.id.rb_btn1)
    RadioButton rb_btn1;
    @BindView(R.id.rb_btn2)
    RadioButton rb_btn2;
    @BindView(R.id.rb_btn3)
    RadioButton rb_btn3;
    @BindView(R.id.rf_ob_shop)
    SmartRefreshLayout rf_ob_shop;
    @BindView(R.id.dragview)
    ImageView mDragview;
    @BindView(R.id.rele)
    RelativeLayout rele;
    @BindView(R.id.titleBar)
    RelativeLayout titleBar;
    private ArrayList<String> titles = new ArrayList<>();
    private ArrayList<ObShopFragment> fragments = new ArrayList<>();
    private List<ObShopTitleBean.MapListBean> mapList = new ArrayList<>();
    private List<ObShopTitleBean.BannerListBean> bannerList = new ArrayList<>();

    private ObShopAdapter adapter;
    private List<ObShopBean.PBean.PageItemsBean> mBeanList = new ArrayList<>();
    private int tag;
    private int page = 1;

    //0正序1倒序
    private int orderType = 0;
    //排序0綜合1銷量2价格
    private int orderBy = 0;
    //查询类型0根据商品分类1搜索2推荐
    private int type = 2;
    //目录ID|搜索内容
    private String content = new String();
    //分类页面
    public static int PAGE_INDEX = 0;
    //是否切换标签
    private boolean isChangeSort = false;
    //是否是搜索回调
    private boolean isEventTag = false;
    private float mOriginalX, mOriginalY;//手指按下时的初始位置
    private float lastX, lastY; //最后一次触摸事件的坐标
    private int containerWidth, containerHeight;    //容器宽高

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ob_shop);
        ButterKnife.bind(this);

        QMUIStatusBarHelper.translucent(this);
        setTitleBarMargin();
        EventBus.getDefault().register(this);
        initData();
        initView();

        initRefreshView();
        initScrollView();
//        initTabLayout();
//        initViewPager();
        initLottery();


    }

    private void initLottery() {
        rele.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                //不能直接在onCreate()方法中得到宽高,会得到0,所以注册视图树的观察者来得到宽高
                //OnPreDrawListener是当一个视图树将要绘制时，所要调用的回调函数的接口类
                containerWidth = rele.getWidth();
                containerHeight = rele.getHeight();
                return true;
            }
        });

        mDragview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //记录触摸时的坐标,这里为什么要用getRawX()和getRawY()相信理解getX(),getY()和getRawX(),getRawY()的区别就知道为什么了
                        lastX = motionEvent.getRawX();
                        lastY = motionEvent.getRawY();
                        mOriginalX = motionEvent.getRawX();
                        mOriginalY = motionEvent.getRawY();
                        //return true对事件进行拦截,不继续下发,防止继续响应onClick事件.
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        //每次移动的距离
                        float distanceX = motionEvent.getRawX() - lastX;
                        float distanceY = motionEvent.getRawY() - lastY;

                        //控件将要移动到的位置,先计算一下,不在ofFloat()方法中再计算是因为要防止控件移动到容器之外.
                        float nextX = mDragview.getX() + distanceX;
                        float nextY = mDragview.getY() + distanceY;
                        //如果将要移动到的 x 轴坐标小于0,则等于0,防止移出容器左边
                        if (nextX < 0)
                            nextX = 0;
                        //防止移出容器右边
                        if (nextX > containerWidth - mDragview.getWidth())
                            nextX = containerWidth - mDragview.getWidth();
                        //防止移出容器顶边
                        if (nextY < 0)
                            nextY = 0;
                        //防止移出容器底边
                        if (nextY > containerHeight - mDragview.getHeight())
                            nextY = containerHeight - mDragview.getHeight();
                        //利用属性动画改变控件的x,y坐标
                        ObjectAnimator mObjectAnimatorX = ObjectAnimator.ofFloat(mDragview, "x", mDragview.getX(), nextX);
                        ObjectAnimator mObjectAnimatorY = ObjectAnimator.ofFloat(mDragview, "y", mDragview.getY(), nextY);
                        AnimatorSet mAnimatorSet = new AnimatorSet();
                        mAnimatorSet.playTogether(mObjectAnimatorX, mObjectAnimatorY);
                        mAnimatorSet.setDuration(0);
                        mAnimatorSet.start();
                        //移动完之后记录当前坐标
                        lastX = motionEvent.getRawX();
                        lastY = motionEvent.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(motionEvent.getRawX() - mOriginalX) <
                                Utils.dp2px(ObShopActivity.this, 3) &&
                                Math.abs(motionEvent.getRawY() - mOriginalY) <
                                        Utils.dp2px(ObShopActivity.this, 3)) {
                            CarActivity.go(ObShopActivity.this);
                        }
                        break;
                }
                return false;
            }
        });
    }

    private void initRefreshView() {

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
        rv_ob_shop.setLayoutManager(gridLayoutManager);
        rv_ob_shop.setNestedScrollingEnabled(false);
        adapter = new ObShopAdapter(mBeanList);
        rv_ob_shop.setAdapter(adapter);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //商品详情
                final ObShopBean.PBean.PageItemsBean item = (ObShopBean.PBean.PageItemsBean) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_item_view:
                        Intent intent = new Intent(ObShopActivity.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", item.getId() + "");
                        intent.putExtra("tag", Constants.OB_TYPE);
                        startActivity(intent);
                        break;
                    case R.id.iv_search_car: {
                        Intent intentP = new Intent(ObShopActivity.this, ShopDetailActivity.class);
                        intentP.putExtra("goodsId", item.getId() + "");
                        intentP.putExtra("show", 1);
                        intentP.putExtra("tag", Constants.OB_TYPE);
                        startActivity(intentP);
                        break;
                    }
                }
            }
        });
//        rf_ob_shop.setEnableAutoLoadmore(false);//禁止加载smartRefresh的加载更多
//        rf_ob_shop.setOnRefreshListener(this);//下拉刷新监听
//        rf_ob_shop.setEnableOverScrollBounce(false);//是否启用越界回弹
    }

    private void initScrollView() {
//        mSvFirst.setInterceptTouchEvent(true);
//        mSvFirst.setDetailScrollStateListener(this);
//        mSvFirst.setScrollViewListener(this);
    }

    //view监听
    private void initView() {
        changeSortIcom(R.mipmap.iv_ob_shop_none);
        rg_ob_shop.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_btn1:
                    case R.id.rb_btn2:
                    case R.id.rb_btn3:
                        orderType = 0;
                        isChangeSort = true;
                        changeSortIcom(R.mipmap.iv_ob_shop_none);
                        break;
                }
            }
        });

        vp_ob_shop.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    type = 2;
                } else {
                    type = mapList.get(position - 1).getId();
                }
                rg_ob_shop.check(R.id.rb_btn1);
                orderBy = 0;
                orderType = 0;
                PAGE_INDEX = position;
                if (!isEventTag) {
                    fragments.get(position).sortAndSearchData(type, orderBy, "", orderType);
                }
                isEventTag = false;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        rf_ob_shop.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                tag = 0;
                page = 1;
                //下拉充值数据
                content = "";
                fragments.get(PAGE_INDEX).initData();
                mPresenter.getListData(ObShopActivity.this, page + "", orderBy + "", type + "", content, orderType + "");
            }
        });

        rf_ob_shop.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                tag = 0;
                page = 1;
                //下拉充值数据
                content = "";
                fragments.get(PAGE_INDEX).initData();
                mPresenter.getListData(ObShopActivity.this, page + "", orderBy + "", type + "", content, orderType + "");
            }
        });

        rf_ob_shop.setEnableAutoLoadmore(true);

        rf_ob_shop.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                tag = 1;
                page = page + 1;
//                fragments.get(PAGE_INDEX).initData();
                mPresenter.getListData(ObShopActivity.this, page + "", orderBy + "", type + "", content, orderType + "");
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                tag = 0;
                page = 1;
                //下拉重置数据
                content = "";
//                fragments.get(PAGE_INDEX).initData();
                mPresenter.getListData(ObShopActivity.this, page + "", orderBy + "", type + "", content, orderType + "");
            }
        });

    }

    //获取标签和列表数据
    private void initData() {
        mPresenter.getObData(this);
        mPresenter.getListData(this, page + "", orderBy + "", type + "", content, orderType + "");

    }

    private void initAdapter() {

        ObShopFragmentApader adapter = new ObShopFragmentApader(getSupportFragmentManager(), fragments, titles);

        vp_ob_shop.setAdapter(adapter);

        ob_shop_tab.setViewPager(vp_ob_shop);

        ob_shop_tab.getTitleView(0).setTypeface(Typeface.DEFAULT_BOLD);

        if (bannerList.size() != 0) {
            vp_ob_shop_banner.setAdapter(new PagerAdapter() {
                @Override
                public int getCount() {
                    return bannerList.size();
                }

                @Override
                public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                    return view == object;
                }

                @Override
                public View instantiateItem(ViewGroup container, int position) {
                    ImageView imageView = new ImageView(ObShopActivity.this);
                    GlideUtils.loadRoundImg(ObShopActivity.this, imageView, bannerList.get(position).getImgPath(), 5);
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    container.addView(imageView);
                    return imageView;
                }

                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                    container.removeView((View) object);
                }

            });
        } else {
            vp_ob_shop_banner.setVisibility(View.GONE);
        }
    }

    //排序选择
    private void changeSort(int orderBy) {
        orderType = orderType == 0 ? 1 : 0;
        this.orderBy = orderBy;
        if (isChangeSort) {
            orderType = 0;
            isChangeSort = false;
            changeSortIcom(R.mipmap.iv_ob_shop_none);
        } else {
            if (orderType == 0) {
                changeSortIcom(R.mipmap.ob_shop_sort_down);
            } else {
                changeSortIcom(R.mipmap.ob_shop_sort_top);
            }
        }
        //加载数据
        fragments.get(PAGE_INDEX).sortAndSearchData(type, orderBy, content, orderType);

    }

    //设置排序图标
    private void changeSortIcom(int rid) {
        Drawable drawable_me = getResources().getDrawable(rid);
        drawable_me.setBounds(0, 0, 15, 30);
        rb_btn3.setCompoundDrawables(null, null, drawable_me, null);
    }

    //设置tab text size
    private void setTabTextSize(int position) {
//        for (int x = 0; x < titles.size(); x++) {
//            if (x == position) {
////                ob_shop_tab.getTitleView(x).setTextSize(ScreenUtil.px2sp(ObShopActivity.this,16));
//            } else {
////                ob_shop_tab.getTitleView(x).setTextSize(ScreenUtil.px2sp(ObShopActivity.this,14));
//            }
//        }
    }

    @OnClick({R.id.tv_search, R.id.iv_shop_back, R.id.iv_ob_shop_vip, R.id.rb_btn1, R.id.rb_btn2, R.id.rb_btn3})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                Intent intent = new Intent(this, SearchActivity.class);
                intent.putExtra("ob_shop", 0);
                startActivity(intent);
                break;
            case R.id.iv_shop_back:
                finish();
                break;
            case R.id.rb_btn1:
                rb_btn1.setChecked(true);
                if (fragments.size() >= 1)
                    changeSort(0);
                break;
            case R.id.rb_btn2:
                rb_btn2.setChecked(true);
                if (fragments.size() >= 1)
                    changeSort(1);
                break;
            case R.id.rb_btn3:
                rb_btn3.setChecked(true);
                if (fragments.size() >= 1)
                    changeSort(2);
                break;
            case R.id.iv_ob_shop_vip:
//                startActivity(new Intent(this, UpVipActivity.class));
                startActivity(new Intent(this, JoinMemberActivity.class));
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        int code = event.getCode();
        if (code == Constants.EventCode.OB_SERACH_BACK) {
            isEventTag = true;
            String search = (String) event.getData();
            rg_ob_shop.check(R.id.rb_btn1);
            ob_shop_tab.setCurrentTab(0);
            vp_ob_shop.setCurrentItem(0);
            orderBy = 0;
            orderType = 0;
            PAGE_INDEX = 0;
            fragments.get(PAGE_INDEX).sortAndSearchData(1, orderBy, search, orderType);
        }
//        else if (code == Constants.EventCode.OB_SHOP_BACK1) {
//            rf_ob_shop.setLoadmoreFinished(false);
//            rf_ob_shop.finishRefresh();
//        } else if (code == Constants.EventCode.OB_SHOP_BACK2) {
//            rf_ob_shop.finishLoadmore();
//        } else if (code == Constants.EventCode.OB_SHOP_BACK3) {
//            rf_ob_shop.setLoadmoreFinished(true);
//        }
    }

    /**
     * 设置沉浸式状态栏时，要把标题栏往下移动状态栏的高度
     */
    protected void setTitleBarMargin() {
        int length = AppUtils.getStatusBarHeight(this);
        //注意布局是哪种Layout
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(titleBar.getLayoutParams());
        lp.setMargins(0, length, 0, 0);
        titleBar.setLayoutParams(lp);
    }

    @Override
    public void showObData(ObShopTitleBean bean) {

        mapList = bean.getMapList();
        ObShopFragment f1 = new ObShopFragment(2);
        fragments.add(f1);
        titles.add("推荐");
        for (ObShopTitleBean.MapListBean mapBean : mapList) {
            ObShopFragment fragment = new ObShopFragment(mapBean.getId());
            fragments.add(fragment);
            titles.add(mapBean.getName());
        }
        bannerList = bean.getBannerList();
        initAdapter();

    }

    @Override
    public void showListData(ObShopBean bean) {

        if (tag == 0) {

            EventBus.getDefault().post(new EventBean(Constants.EventCode.OB_SHOP_BACK1, null));
            rf_ob_shop.setLoadmoreFinished(false);
            rf_ob_shop.finishRefresh();
            mBeanList.clear();
            if (bean.getP().getPageItems().size() == 0) {
//                ll_no_data.setVisibility(View.VISIBLE);
                rv_ob_shop.setVisibility(View.GONE);
            } else {
//                ll_no_data.setVisibility(View.GONE);
                rv_ob_shop.setVisibility(View.VISIBLE);
            }
        } else if (tag == 1) {
            EventBus.getDefault().post(new EventBean(Constants.EventCode.OB_SHOP_BACK2, null));
            rf_ob_shop.finishLoadmore();
        }
        mBeanList.addAll(bean.getP().getPageItems());
        adapter.notifyDataSetChanged();
        if (bean.getP().getPageItems().size() == 0 || bean.getP().getPageSize() * bean.getP().getPageNumber() >= bean.getP().getPageTotle()) {
            EventBus.getDefault().post(new EventBean(Constants.EventCode.OB_SHOP_BACK3, null));
            rf_ob_shop.setLoadmoreFinished(true);//将不会再次触发加载更多事件
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

//    @Override
//    public boolean isChildTouchEvent() {
//        ObShopFragment fragment = fragments.get(vp_ob_shop.getCurrentItem());
//        return fragment.canChildTouch();
//    }
//
//
//    @Override
//    public void updateTouchEvent(boolean isInterceptTouchEvent) {
//        if (mSvFirst != null)
//            mSvFirst.setInterceptTouchEvent(isInterceptTouchEvent);
//    }
//
//    @Override
//    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
//        int[] location = new int[2];
//        vp_ob_shop.getLocationOnScreen(location);
//        int yPosition = location[1];
////        int visibility = mTopTabLayout.getVisibility();
//        if (yPosition < vp_ob_shop.getHeightOffset()) {//移动到顶部，小于顶部偏移量(ViewPager完全显示)
//            updateTouchEvent(false);
////            if(visibility != View.VISIBLE)
////                mTopTabLayout.setVisibility(View.VISIBLE);
//        } else {
//            updateTouchEvent(true);
////            if(visibility != View.GONE)
////                mTopTabLayout.setVisibility(View.GONE);
//        }
//    }
//
//    @Override
//    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//        refreshLayout.finishRefresh(2000);
//    }
}
